package dofix;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcity.game.skill.state.Phase;
import com.xcity.game.skill.state.State;

public class PlayerSkillFix {

	public static void main(String[] args) throws Exception {
		String url = args[0];
//		jdbc:mysql://rdsd09ffm5143cy22qd4.mysql.rds.aliyuncs.com:3306/platform?characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
		if (!url.startsWith("jdbc:")) {
			url = "jdbc:mysql://" + url + "?characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true";
		}
		String user = args[1];
		String password = args[2];
		Connection conn = DriverManager.getConnection(url, user, password);
		try {
			PreparedStatement ps = conn.prepareStatement("select id, skills from player_ext where skills is not null and skills != '[]'");
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				long id = rs.getLong(1);
				String s = rs.getString(2);
				tryFix(conn, id, JSON.parseArray(s));
			}
			rs.close();
			ps.close();
		} finally {
			conn.close();
		}
	}
	
	static void tryFix(Connection conn, long id, JSONArray skills) throws Exception {
		boolean fix = false;
		for (int i = 0; i < skills.size(); i++) {
			JSONObject skill = skills.getJSONObject(i);
			
			int exp = skill.getIntValue("exp") * 60;
			skill.put("exp", exp);
			JSONObject phase = skill.getJSONObject("phase");
			if (phase.getIntValue("id") == Phase.PRACTICE.ordinal()) {
				phase.put("id", Phase.STUDY.ordinal());
				if (phase.getByteValue("state") == Phase.STATE_RUNNING) {
					skill.put("state", State.UNACTIVATED.ordinal());
				}
			}
			fix = true;
			
			skills.set(i, skill);
		}
		PreparedStatement ps = conn.prepareStatement("update player_ext set skills = ? where id = ?");
		ps.setString(1, skills.toJSONString());
		ps.setLong(2, id);
		ps.executeUpdate();
		ps.close();
		System.out.println("skill fixed: " + id + "," + fix);
	}
	
}
